<template>
  <div id="client">
    <p style="margin-left: 20px">
      客户：
      <el-input
        style="width: 200px; margin-left: 0px; margin-right: 20px"
        placeholder="客户编号"
        v-model="salesReturn.customername"
        clearable
      >
      </el-input>
      <el-button
        style="margin-left: -20px; margin-right: 10px"
        @click="dialogFormVisible3 = true"
        >...</el-button
      >
      &nbsp;&nbsp;&nbsp; 销售人员
      <el-select
        v-model="salesReturn.saler"
        placeholder="销售人员"
        style="width: 100px"
      >
        <el-option
          v-for="item in salemen"
          :key="item.employeeId"
          :label="item.employeeName"
          :value="item.employeeCode"
        >
        </el-option> </el-select
      >&nbsp;&nbsp;&nbsp;
      <span class="returnDate">单据日期：</span>
      <el-date-picker
        v-model="salesReturn.returnDate"
        type="datetime"
        placeholder="选择日期时间"
        value-format="yyyy-MM-dd HH:mm:ss"
      >
      </el-date-picker
      >&nbsp;&nbsp;&nbsp; 地址
      <el-select
        v-model="salesReturn.address"
        placeholder="地址"
        style="width: 200px"
      >
        <el-option
          v-for="item in addresses"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option> </el-select
      >&nbsp;&nbsp;&nbsp;
    </p>
    <el-divider></el-divider>
    <div style="margin-bottom: 20px; margin-right: 20px; float: right">
      <el-button @click="doAdd()" v-show="salesReturn.status == ''"
        >保存</el-button
      >&nbsp;&nbsp;&nbsp;
      <el-button
        type="primary"
        @click="toSubmit()"
        v-show="salesReturn.status == 0"
        >提交</el-button
      >&nbsp;&nbsp;&nbsp;
      <el-button type="warning" v-show="salesReturn.status == 2"
        >反审核</el-button
      >&nbsp;&nbsp;&nbsp;
      <el-button type="primary">批量导入</el-button>&nbsp;&nbsp;&nbsp;
    </div>
    <div style="margin-top: 30px">
      <el-table
        height="300px"
        :data="tableData"
        border
        style="width: 100%; font-size: 13px"
        @current-change="handleCurrentChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="removeRow(scope.$index)"
              >删除</el-button
            >
            <el-button size="mini" @click="addRow">添加</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="商品" width="230">
          <template slot-scope="scope">
            <el-input
              style="width: 120px; margin-left: 10px; margin-right: 20px"
              placeholder="商品"
              v-model="scope.row.goodname"
              clearable
            ></el-input>
            <el-button
              style="margin-left: -20px; margin-right: 10px; width: 50px"
              @click="goodsShow = true"
              >...</el-button
            >
          </template>
        </el-table-column>

        <el-table-column prop="imagename" label="图片" width="120">
        </el-table-column>
        <el-table-column prop="unitname" label="基本单位" width="120">
        </el-table-column>
        <el-table-column prop="totalNum" label="总可退数量" width="120">
        </el-table-column>

        <el-table-column label="仓库" width="120">
          <template slot-scope="scope">
            <el-select v-model="scope.row.stocknum">
              <el-option
                v-for="store in storeList"
                :key="store.shId"
                :label="store.storeHomeName"
                :value="store.shId"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="totalreturnnum" label="总退货数量" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.totalreturnnum"
              placeholder="总退款数量"
              @input="calculateTotalPrice(scope.$index)"
              clearable
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="unitCost" label="单价/元" width="120">
        </el-table-column>
        <el-table-column prop="discount" label="折扣率%" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.discount"
              placeholder="折扣率"
              @input="calculateTotalPrice(scope.$index)"
              clearable
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="tax" label="税率%" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.tax"
              placeholder="税率"
              @input="calculateTotalPrice(scope.$index)"
              clearable
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="折后含税单价/元" width="120">
        </el-table-column>
        <el-table-column
          prop="totalreturnmoney"
          label="总退款金额/元"
          width="120"
        >
        </el-table-column>
        <!-- <el-table-column prop="yesreturnnum" label="已退款数量" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.yesreturnnum"
              placeholder="已退款数量"
              clearable
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="yesreturnmoney"
          label="已退款金额/元"
          width="120"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.yesreturnmoney"
              placeholder="已退款金额"
              clearable
            ></el-input>
          </template>
        </el-table-column> -->

        <el-table-column prop="remark" label="备注" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.remark"
              placeholder="备注"
              clearable
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="addRow">添加行</el-button>
      <el-input
        type="textarea"
        :rows="2"
        placeholder="暂无备注信息"
        v-model="salesReturn.remark"
        style="width: 100%; line-height: 20px"
      >
      </el-input>
      <p style="margin-top: 20px">
        总金额：
        <el-input
          style="width: 200px; margin-left: 10px; margin-right: 20px"
          placeholder="退款总金额"
          v-model="salesReturn.totalReturnPrice"
          disabled
          clearable
        >
        </el-input
        >&nbsp;&nbsp; 本次退款：<el-input
          style="width: 200px; margin-left: 10px; margin-right: 20px"
          placeholder="本次退款"
          v-model="salesReturn.nowreturn"
          @input="calculatereturn()"
          clearable
        >
        </el-input
        >&nbsp;&nbsp; 结算账户：
        <el-select
          v-model="salesReturn.account"
          placeholder="结算账户"
          style="width: 100px"
        >
          <el-option
            v-for="item in accounts"
            :key="item.accountCode"
            :label="item.aTypeName"
            :value="item.accountCode"
          >
          </el-option>
        </el-select>
      </p>
      <p style="margin-top: 20px; width: 1350px">
        &nbsp;&nbsp; 本次欠款：<el-input
          style="width: 200px; margin-left: 10px; margin-right: 20px"
          placeholder="本次欠款"
          v-model="salesReturn.nownopay"
          disabled
          clearable
        >
        </el-input
        >&nbsp;&nbsp;&nbsp; <span class="demonstration">收款到期日：</span>
        <el-date-picker
          v-model="salesReturn.payDueDate"
          type="datetime"
          placeholder="收款到期日"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </p>

      <p style="margin-top: 20px; margin-right: 20px; height: 100px">
        <span style="display: inline-block; float: right">
          <el-button @click="goto('returnOrderList')">历史单据</el-button
          >&nbsp;&nbsp; <el-button>操作日志</el-button></span
        >
      </p>
    </div>

    <el-dialog top="20px" title="选择客户" :visible.sync="dialogFormVisible3">
      <ClientChoose
        ref="customerCode"
        :dialogFormVisible3="dialogFormVisible3"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="yesCustomer">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog top="20px" title="选择商品" :visible.sync="goodsShow">
      <GoodsChoose ref="chooseGoods" :goodsShow="goodsShow" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="goodsShow = false">取 消</el-button>
        <el-button type="primary" @click="yesGoods">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import GoodsChoose from "../public_com/GoodsChoose.vue";
import ClientChoose from "../public_com/ClientChoose.vue";

export default {
  name: "SaleOrder",
  components: {
    GoodsChoose,
    ClientChoose,
  },
  data() {
    return {
      goodsShow: false,
      salesReturn: {
        status: "",
        customername: "",
        nowreturn: 0,
        remark: "",
        returnDate: "", // 销货单据日期
        id: "",
        account: "",
        logisticsNum: "",
        customerNum: "", // 客户编号
        saler: "", // 销售人员编号
        address: "", // 地址
        totalReturnPrice: 0, // 总金额
        nownopay: 0, //本次欠款
        payDueDate: "", // 收款到期日
      },

      // 销售人员列表伪数据
      salemen: [],
      id: "",
      // 地址列表伪数据
      addresses: [
        { id: 1, name: "地址1" },
        { id: 2, name: "地址2" },
        { id: 3, name: "地址3" },
      ],
      storeList: [],
      accounts: [],
      dialogFormVisible1: false,
      dialogFormVisible: false,
      dialogFormVisible3: false,
      tableData: [
        {
          totalreturnmoney: 0,
          yesreturnmoney: 0,
          totalreturnnum: 0,
          yesreturnnum: 0,

          gId: "",
          goodname: "",
          unitname: "",
          unitId: "",
          stocknum: "",
          totalNum: "",
          totalPrice: 0,
          tax: 0,
          discount: 0,
          // giveGoods: "",
          unitCost: 0,
          rid: "",
        },
      ],
    };
  },
  created() {
    this.getStoreList();
    this.getAccounts();
    this.getSaler();
    var id = this.$route.params.id;
    if (typeof id === "undefined") {
      this.id = "";
    } else {
      this.id = id;
      this.getSaleOrder(this.id);
      this.getbyrid(this.id);
    }
    console.log("类型" + typeof this.salesReturn.address);
  },
  methods: {
    // salesReturn
    toSubmit: function () {
      if (!this.validateData()) {
        return;
      }

      var dataFormat = new FormData();
      if (this.id !== "") {
        this.salesReturn.id = this.id;
      }
      dataFormat = {
        salesReturn: JSON.stringify(this.salesReturn),
      };
      this.axios
        .post("/erp/sale/salesReturn/git", {
          ...dataFormat,
        })
        .then((rs) => {
          if (rs.data.result == true) {
            alert("提交成功！");
          } else {
            alert("提交失败！");
          }
        })
        .catch((error) => {
          console.error("Error:", error);
        });
    },
    getStoreList() {
      this.axios
        .get("/info/storeHouse/getAllStore", {
          params: {
            cId: 1,
          },
        })
        .then((rs) => {
          this.storeList = rs.data.storeList;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    calculatereturn() {
      this.salesReturn.nownopay =
        this.salesReturn.totalReturnPrice - this.salesReturn.nowreturn;
    },
    calculateTotalPrice(index) {
      var price = 0;
      const row = this.tableData[index];
      row.totalPrice =
        (1 - row.tax / 100) * (1 - row.discount / 100) * row.unitCost;
      row.totalreturnmoney = row.totalPrice * row.totalreturnnum;
      this.tableData.forEach((item) => {
        price = price + item.totalreturnmoney;
      });
      this.salesReturn.totalReturnPrice = price;
    },
    getAccounts: function () {
      this.axios({
        url: "/info/account/selectAll",
      })
        .then((rs) => {
          this.accounts = rs.data.accounts;
          console.log("myaccounts", this.accounts);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getSaler() {
      this.axios({
        url: "/info/employee/listAll",
      })
        .then((rs) => {
          this.salemen = rs.data.list;
          console.log("saleMan", rs.data);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    yesCustomer() {
      this.dialogFormVisible3 = false;
      this.salesReturn.customerNum = this.$refs.customerCode.clientCode;
      this.salesReturn.customername = this.$refs.customerCode.clientName;
    },
    getbyrid(rid) {
      this.axios({
        url: "/erp/sale/salesReturnDetail/selectByRid",
        params: {
          rid,
        },
      }).then((rs) => {
        this.tableData = rs.data.result;
        console.log("tableData", this.tableData);
      });
    },
    getSaleOrder(id) {
      this.axios({
        url: "/erp/sale/salesReturn/selectById",
        params: {
          id,
        },
      }).then((rs) => {
        console.log("salesReturnbyid", rs.data.result);
        this.salesReturn = rs.data.result;
      });
    },
    addRow() {
      this.tableData.push({
        totalreturnmoney: 0,
        yesreturnmoney: 0,
        totalreturnnum: 0,
        yesreturnnum: 0,

        gId: "",
        goodname: "",
        unitname: "",
        unitId: "",
        stocknum: "",
        totalNum: "",
        totalPrice: 0,
        tax: 0,
        discount: 0,
        // giveGoods: "",
        unitCost: 0,
        rid: "",
      });
    },
    removeRow(index) {
      this.tableData.splice(index, 1);
    },

    yesGoods() {
      this.goodsShow = false;
      // var detailList = this.$refs.chooseGoods.selectionList;
      var indexs = [];
      this.inBoundList = this.$refs.chooseGoods.selectionList;
      const rid = this.id;
      this.inBoundList.forEach((item) => {
        this.tableData.push({
          totalreturnmoney: 0,
          yesreturnmoney: 0,
          totalreturnnum: 0,
          yesreturnnum: 0,
          gId: item.gid,
          goodname: item.goodname,
          unitname: item.unitname,
          unitId: item.unitId,
          stocknum: item.defaultStock,
          totalNum: "",
          totalPrice: 0,
          tax: 0,
          discount: 0,
          // giveGoods: item.giveGoods,
          unitCost: item.unitCost,
          rid: rid,
        });
        var index1 = [];
        this.tableData.forEach((detail, index) => {
          if (detail.gId == "") {
            index1.push(index);
            console.log(index);
          }
        });
        index1.reverse().forEach((index, i) => {
          console.log(index);
          this.tableData.splice(index, 1);
        });
        console.log("tableData", this.tableData);
      });
    },

    doAdd() {
      if (!this.validateData()) {
        return;
      }
      if (this.id !== "") {
        this.salesReturn.id = this.id;
        this.axios
          .post("/erp/sale/salesReturn/update", {
            salesReturn: this.salesReturn, // 发送 salesReturn 对象
            tableData: this.tableData, // 发送 tableData 数组
          })
          .then((rs) => {
            if (rs.data.result == true) {
              alert("修改成功！");
              this.goto("returnOrderList");
            } else {
              alert("修改失败！");
            }
          })
          .catch((error) => {
            console.error("Error:", error);
          });
      } else {
        console.log("tabledata", this.tableData);
        console.log("salesreturn", this.salesReturn);
        const formData = new FormData();
        formData.append("salesReturn", JSON.stringify(this.salesReturn));
        formData.append("tableData", JSON.stringify(this.tableData));
        this.axios
          .post(
            "/erp/sale/salesReturn/insert",
            // salesReturn: this.salesReturn, // 发送 salesReturn 对象
            // tableData: this.tableData, // 发送 tableData 数组
            formData
          )
          .then((rs) => {
            if (rs.data.result == true) {
              alert("添加成功！");
              this.goto("returnOrderList");
            } else {
              alert("添加失败！");
            }
          })
          .catch((error) => {
            console.error("Error:", error);
          });
      }
    },

    goto(to) {
      this.$router.push(to);
    },
    validateData() {
      let errors = [];

      // 验证 salesReturn 字段
      if (!this.salesReturn.customername) {
        errors.push("客户名称不能为空。");
      }
      if (!this.salesReturn.saler) {
        errors.push("销售人员不能为空。");
      }
      if (!this.salesReturn.returnDate) {
        errors.push("单据日期不能为空。");
      }
      if (!this.salesReturn.address) {
        errors.push("地址不能为空。");
      }
      if (!this.salesReturn.account) {
        errors.push("结算账户不能为空。");
      }
      if (!this.salesReturn.payDueDate) {
        errors.push("收款到期日不能为空。");
      }

      // 验证 tableData 中的每个项
      this.tableData.forEach((item, index) => {
        if (!item.goodname) {
          errors.push(`第 ${index + 1} 行：商品名称不能为空。`);
        }
        if (!item.totalreturnnum) {
          errors.push(`第 ${index + 1} 行：总退货数量不能为空。`);
        } else if (isNaN(item.totalreturnnum)) {
          errors.push(`第 ${index + 1} 行：总退货数量必须是数字。`);
        } else if (
          Number(item.totalreturnnum) !== Number(item.totalreturnnum).toFixed(2)
        )
          if (!item.unitCost) {
            errors.push(`第 ${index + 1} 行：单价不能为空。`);
          } else if (isNaN(item.unitCost)) {
            errors.push(`第 ${index + 1} 行：单价必须是数字。`);
          }

        if (!item.discount) {
          errors.push(`第 ${index + 1} 行：折扣率不能为空。`);
        } else if (isNaN(item.discount)) {
          errors.push(`第 ${index + 1} 行：折扣率必须是数字。`);
        }

        if (!item.tax) {
          errors.push(`第 ${index + 1} 行：税率不能为空。`);
        } else if (isNaN(item.tax)) {
          errors.push(`第 ${index + 1} 行：税率必须是数字。`);
        }
      });

      if (errors.length > 0) {
        // 可以选择显示所有错误消息
        alert(errors.join("\n"));
        return false;
      }

      return true;
    },
  },
};
</script>

<style scoped>
.el-button el-button--default el-popover__reference {
  margin-right: 20px;
}

tr {
  border: 1px solid black;
}
</style>